/**
 * <datetimepicker ng-model = 'date_in_float' format=  min-view = start-view today = true ></datetimepicker>
 * @returns {{restrict: string}}
 */

module.exports = ['$timeout', function ($timeout) {
    return {
        restrict: 'E',
        scope   : {
            ngModel  : '=',
            startDate: '=',
            endDate  : '='
        },
        require : 'ngModel',
        template: '<input type="text" >',
        replace : true,
        link    : function (scope, element, attrs, ngModelCtrl) {

            var time;

            function updateDateTime(utc) {
                //console.log('update date', utc);
                time = utc.valueOf();
                ngModelCtrl.$setViewValue(utc.valueOf());
            }

            //讲道理这句话很关键好吧，
            //永远让$modelValue === time
            //为什么呢？这里我们的template是一个input,所以ngModel绑在input上的结果就是
            //angular永远会比较input.value和ngModelCtrl.$viewValue值
            //来确定是否要更新，但是我们不希望它更新，更新方法已经被手动写到$render函数里去了。
            //所以我们要确保input.value和ngModelCtrl.$viewValue永远一致才行
            ngModelCtrl.$parsers.push(function () {
                //console.log('parser', arguments, time);
                //console.log('model.$viewValue', ngModelCtrl.$viewValue, ngModelCtrl.$modelValue);
                //ngModelCtrl.$modelValue = ngModelCtrl.$viewValue;
                //return ngModelCtrl.$viewValue;
                return time;
            });

            ngModelCtrl.$formatters.push(function (val) {
                //console.log('formatter', arguments);
                return val;
            });

            //TODO 需要测试
            ngModelCtrl.$render = function () {
                var local = new Date(Number(ngModelCtrl.$viewValue));
                //var utc = new Date(local.getTime() + (local.getTimezoneOffset() * 60000));
                //console.log('$render', ngModelCtrl.$viewValue, local);
                //scope.date = ctrl.$viewValue;
                //if( typeof  scope._date  === 'number')
                $ele.datetimepicker('setDate', local);
            };

            scope.$watch('ngModel', function (val, old) {
                //console.log(val, old);
                if (val == undefined && old != undefined ) {
                    //console.log("CLEAR" ,val, old);
                    element[0].value = null;
                    element[0].text = null;
                    //$ele.text(null);
                    //$ele.val(null);
                } else if (val !== undefined && val !== old && old === undefined) {
                    //console.log("SET DATE", val, old);
                    time = val;
                    //$ele.datetimepicker('setDate', new Date(val));
                }
                else {
                    //console.log("DO NOTHING");
                }
            });

            var $ele = $(element);

            if (attrs.ngRequired)
                $ele.attr("ng-required", attrs.ngRequired);

            if (attrs.name)
                $ele.attr('name', attrs.name);

            var options = $.extend({
                format   : 'yyyy-mm-dd',
                autoclose: true
            }, attrs);

            var filters = {
                format    : function (v) {
                    return v || 'yyyy-mm-dd'
                },
                todayBtn  : function (v) {
                    return Boolean(v) || false
                },
                minView   : function (v) {
                    return Number(v) || 2;
                },
                maxView   : function (v) {
                    return Number(v) || 4;
                },
                minuteStep: function (v) {
                    return Number(v) || 5;
                },
                startView : function (v) {
                    return Number(v) || 2;
                },
                autoclose : function (v) {
                    return true;
                },
                startDate : function (v) {
                    if (v instanceof Date) {
                        return v;
                    }
                    if (typeof v === 'number') {
                        return new Date(v);
                    }
                    return void 0;
                },
                endDate   : function (v) {
                    if (v instanceof Date) {
                        return v;
                    }
                    if (typeof v === 'number') {
                        return new Date(v);
                    }
                    return void 0;
                }
            };


            for (var i in options) {
                if (options.hasOwnProperty(i)) {
                    if (filters[i] && typeof filters[i] === 'function') {
                        options[i] = filters[i](attrs[i]);
                    }
                    else {
                        delete options[i];
                    }
                }
            }

            //options.forceParse = false;

            $ele.datetimepicker(options)
                .on('changeDate', function (e) {
                    $timeout(function () {
                        updateDateTime(e.date);//utc time
                    }, 0)
                });

            //if (scope.date)$ele.datetimepicker('setDate', new Date(Number(scope.date)));

            if (attrs.title !== void 0 && attrs.title == "false") {
                var $picker = $($ele.data('datetimepicker').picker);
                $picker.find('thead').remove();
                $picker.find('tbody tr td').css({width: "185px"});
            }

            //console.log("picker", $ele.datetimepicker("picker"));

            //scope.$watch('date', function (val, old) {
            //    if (typeof val === 'number' && val !== old){
            //        console.log('date watch triggered' , val, old);
            //        $ele.datetimepicker('setDate', new Date(Number(val)));
            //    }
            //});

            scope.$watch('startDate', function (val, old) {
                //console.log('$watch startDate', val);
                if (val === null) {
                    $ele.datetimepicker('setStartDate', null);
                } else if (val && val !== old) {
                    var new_date;
                    if (val instanceof Date) {
                        new_date = val;
                    }
                    else if (typeof val === 'number') {
                        new_date = new Date(val);
                    }
                    else {
                        return false;
                    }

                    var d = new Date(new_date);
                    $ele.datetimepicker('setStartDate', d);
                }
            });

            scope.$watch('endDate', function (val, old) {
                if (val === null) {
                    $ele.datetimepicker('setEndDate', null);
                } else if (val && val !== old) {
                    var new_date;
                    if (val instanceof Date) {
                        new_date = val;
                    }
                    else if (typeof val === 'number') {
                        new_date = new Date(val);
                    } else {
                        return false;
                    }

                    var d = new Date(new_date);
                    $ele.datetimepicker('setEndDate', d);
                }
            });

        }
    }
}];
